// __PUBLIC__/admin/js/page/cms/article/content
require(['../../common'], function() {
  require(['article.content'])
})

define('article.content', [
  'jquery',
  'page/grid',
  'css!ke/themes/default/default.css',
  'ke/kindeditor',
  'ke/lang/zh_CN',
  'css!ztree/ztree.css',
  'ztree/ztree'
], function($, Grid) {
  'use strict';

  var sid = $('#sid').val();
  var cid = $('#cid').val();
  var jumpUrl = $('#J_generate').attr('data-jumpurl');

    function handleSelected(callback) {
      var selected = mygrid.getSelected()
      if (!selected.count) {
        alert('请选择一条数据')
      } else {
        callback(selected)
      }
    }

    function del(selected) {
      $.post(APP + '?app=cms&m=Article&a=delArticle&sid=' + sid + '&cid=' + cid, {
        ids: selected.id.join(),
        cnum: selected.id.length
      })
        .done(function(data) {
          if (data === '1') {
            mygrid.del(selected.index)
          } else {
            alert('删除失败')
          }
        })
    }

    function operate(selected, type, msg) {
      var ids = selected.id.join()
      $.post(APP + '?app=cms&m=Article&a=oper', {
        ids: ids,
        type: type
      })
        .done(function(res) {
          if (res === '1') {
            alert(msg + '成功')
            location.href = decodeURIComponent(jumpUrl);
          } else {
            alert(msg + '失败')
          }
        })
    }

    /**
     * 发送到播报
     */
    $('.send_as_message').on('click',function(e){
        e.preventDefault();
        var _url = $(this).attr('data-url');
        $.get(_url,function(data){
            alert(data.info);
        });
    });

    /**
     * 添加新文章
     * @param {number} tid article type id
     */

    function add(classId, type) {
      location.href = APP + '?app=cms&m=Article&a=addcontent&sid=' + sid + '&cid=' + cid + '&classId=' + classId + '&type=' + type
    }

    function push(ids) {
      var params = '&sid=' + sid + '&cid=' + cid + '&ids=' + ids
      location.href = APP + '?app=admin&m=Push&a=apppush' + params
    }

    function dropdown(selector) {
      var $drop = $(selector)
      var timeout

      $drop.on('mouseenter', function() {
        clearTimeout(timeout)
        $drop.addClass('open')
      }).on('mouseleave', function() {
        timeout = setTimeout(function() {
          $drop.removeClass('open')
        }, 300)
      })
    }

    function move(id, el, index, nextIndex, direction) {
      var baseid = direction == 'up' ? $(el).closest('tr').prev().data('id') : $(el).closest('tr').next().data('id');
      if (baseid) {
        $.post(APP + '?app=cms&m=Article&a=display_order', {
          id: id,
          baseid: baseid
        }).done(function(res) {
          if (res === '1') {
            mygrid.swap(index, nextIndex)
          }
        })
      }
    }

    var eyeHeight = (function(){
        var winHeight = $(window).height();
        if(winHeight > 620){
            return 600;
        }else{
            return winHeight - 20;
        }
    })();
    function selBlock(selected) {
      var ids = selected.id
      var dialog = KindEditor.dialog({
        width: 400,
        height: eyeHeight,
        title: '选择区块',
        body: '<div id="dialoghtml" style="margin:10px;overflow:auto;">' + '<div class="zTreeDemoBackground left"  style="height:100%;width:181px;overflow:auto;">' + '<ul id="dialog_treeDemo" class="ztree" style="margin-top:10px;"></ul>' + '</div></div>',
        closeBtn: {
          name: '关闭',
          click: function(e) {
            e.preventDefault()
            dialog.remove();
          }
        },
        yesBtn: {
          name: '确定',
          click: function(e) {
            e.preventDefault()
            var treeObj = $.fn.zTree.getZTreeObj("dialog_treeDemo");
            var nodes = treeObj.getCheckedNodes();
            var arr = []
            for (var i = 0; i < nodes.length; i++) {
              if (nodes[i]['isParent'] === false) {
                arr.push(nodes[i]['id']);
              }
            }
            if (arr.length <= 0) {
              alert('请选择区块');
              return false;
            }
            var block_id = arr.toString();
            $.post(APP + '?app=cms&m=Block&a=createBlock&sid=' + sid, {
              arr: ids,
              block_id: block_id
            }, function(msg) {
              if (msg == 1) {
                alert('添加成功');
              } else {
                alert(msg);
              }
            });
            dialog.remove();
          }
        },
        noBtn: {
          name: '取消',
          click: function(e) {
            e.preventDefault()
            dialog.remove();
          }
        }
      });
      var setting = {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            enable: true
          }
        },
      };
      $.ajax({
        async: false,
        cache: false,
        type: 'POST',
        dataType: "json",
        url: APP + '?app=cms&m=Block&a=getBlockInfo', //请求的action路径
        data: {
          id: 1
        },
        success: function(data) { //请求成功后处理函数。
          $.fn.zTree.init($("#dialog_treeDemo"), setting, data['children']);
        }
      });
    }

  KindEditor('#J_block').click(function() {
    handleSelected(function(selected) {
      selBlock(selected)
    })
  })

  dropdown('#J_addmenu')
  $('#J_addmenu').children('.dropdown-menu').on('click', 'a', function(e) {
    e.preventDefault()

    add($(this).data().id, $(this).data().name)
  })

  var $form = $('#J_form')
  var $table = $('.table')
  var mygrid = new Grid($table)
  mygrid.init();

  $table
    .on('click', '.A_del', function() {
      if (confirm('确定删除已选择的内容？')) {
        var current = mygrid.getCurrent(this)
        var selected = {
          id: [current.id],
          index: [current.index]
        }
        del(selected)
      }

    })
  // 排序
  .on('click', '.moveup', function(e) {
    if ($(this).hasClass('disabled')) {
      return false
    }
    move($(this).closest('tr').data('id'), this, mygrid.getIndex(this), Number(mygrid.getIndex(this) - 1), 'up')
  })

  // 排序
  .on('click', '.movedown', function(e) {
    if ($(this).hasClass('disabled')) {
      return false
    }
    move($(this).closest('tr').data('id'), this, mygrid.getIndex(this), Number(mygrid.getIndex(this) + 1), 'down')
  })

  $('#J_del').on('click', function(e) {
    e.preventDefault()
    handleSelected(function(selected) {
      if (confirm('确定删除已选择的内容？')) {
        del(selected)
      }
    })
  })

  $('#J_review').on('click', function(e) {
    e.preventDefault()
    handleSelected(function(selected) {
      operate(selected, 'sh', '审核')
    })
  })

  $('#J_generate').on('click', function(e) {
    e.preventDefault()
    handleSelected(function(selected) {
      operate(selected, 'publish', '生成')
    })
  })

  $('#J_push').on('click', function(e) {
    e.preventDefault()
    handleSelected(function(selected) {
      if (confirm('确定推送已选择的内容')) {
        push(selected.id.join())
      }
    })
  })

})